<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Config, UserAuth, UserSafety, HallTrade, HallApple, CoinsPrice, UserConfig, Moneylog};
use think\Facade\Config as Configs;
use think\Validate;
use think\Db;

class Hall extends Base
{
    //大厅
    public function lists()
    {
        $type = $this->request->get('type/d', '');
        $list = (new HallTrade())->order('price desc')->where('status', 1);
        if (!empty($type)) {
            $list = $list->where('type', $type);
        }
        $list = $list->where('buyer_id|seller_id', '<>', $this->request->user_id)->field('logid,status,trade_type,payimages,created,paycreated,updated', true)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['nickname'] =  (new Users())->where('id', $lists['user_id'])->value('nickname');
            if ($lists['buyer_id'] > 0) {
                $lists['buyer_level'] = (new Users())->where('id', $lists['buyer_id'])->value('level');
            }
            if ($lists['seller_id'] > 0) {
                $lists['seller_level'] = (new Users())->where('id', $lists['seller_id'])->value('level');
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function MoneyLog()
    {
        $type = $this->request->get('type/d', '');
        $list = (new Moneylog())->order('id desc')->where('user_id', $this->request->user_id);
        if (!empty($type)) {
            $list = $list->where('cointype', $type);
        }
        $list = $list->field('money,info,created')->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '获取成功');
    }

    //大厅
    public function hallother()
    {
        $list['price'] = (new CoinsPrice())->where('date', date('Y-m-d'))->value('price');
        $list['price'] = !empty($list['price']) ? $list['price'] : 0;
        $list['reputa'] = (new Users())->where('id', $this->request->user_id)->value('reputa');
        $list['buytotal'] = (new HallTrade())->where('status', 1)->where('type', 1)->sum('num');
        $list['selltotal'] = (new HallTrade())->where('status', 1)->where('type', 2)->sum('num');
        $list['handfee'] = (new UserConfig())->where('level', $this->request->user['level'])->value('handfee');
        $this->result($list, 0, '获取成功');
    }

    public function ReleOrder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require|in:1,2',
                'num' => 'require|gt:0|number',
                'price' => 'require|gt:0',
                'trade' => 'require'
            ], [
                'type.require' => '订单类型不能为空',
                'type.in' => '订单类型错误',
                'num.require' => '交易数量不能为空',
                'num.gt' => '交易数量必须大于0',
                'num.number' => '交易数量必须是整数',
                'price.require' => '交易价不能为空',
                'price.gt' => '交易价必须大于0',
                'trade.require' => '交易密码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if (md5(md5($data['trade'])) != $user['trade']) {
                $this->result([], 1, '交易密码错误');
            }
            if ($user['reputa'] < 1) {
                $this->result([], 1, '信誉值过低');
            }
            $config = (new Config())->where('key', 'hall')->value('value');
            $config = json_decode($config, true);
            if (empty($config['min']) || empty($config['max']) || empty($config['allmax']) || empty($config['count'])) {
                $this->result([], 1, '系统参数错误');
            }
            if ($config['min'] > $data['num']) {
                $this->result([], 1, '单次发布数量范围在' . $config['min'] . '~' . $config['max'] . '之间');
            }
            $transopen = (new Config())->where('key', 'transopen')->value('value');
            $transopen = empty($transopen) ? 2 : $transopen;
            if ($transopen != 1) {
                $this->result([], 1, '交易市场已关闭');
            }
            //价格范围
            $price = (new CoinsPrice())->where('date', date('Y-m-d'))->value('price');
            $price = !empty($price) ? $price : 0;
            $hallrange = (new Config())->where('key', 'hallrange')->value('value');
            $hallrange = empty($hallrange) ? 5 / 100 : $hallrange / 100;
            $minprice = round((1 - $hallrange) * $price, 2);
            $maxprice = round((1 + $hallrange) * $price, 2);
            if ($minprice > $data['price'] || $data['price'] > $maxprice) {
                $this->result([], 1, '挂单价格范围必须在' . $minprice . '~' . $maxprice . '之间');
            }
            //是否实名
            $auth = (new UserAuth())->where('user_id', $this->request->user_id)->find();
            if (empty($auth) || $auth['status'] != 2) {
                $this->result([], 1, '未进行身份认证，无法发布交易');
            }
            $safety = (new UserSafety())->where(['user_id' => $this->request->user_id, 'type' => [1, 2, 3]])->count();
            if ($safety < 3) {
                $this->result([], 1, '请先绑定微信、支付宝和银行卡等收、付款信息');
            }
            //有交易中的订单无法继续发布
            $haveorder = (new HallTrade())->where('buyer_id|seller_id', $this->request->user_id)->where(['status' => [1, 2, 3, 6, 7]])->count();
            if ($haveorder > 0) {
                $this->result([], 1, '请先完成交易订单再继续操作');
            }
            //每天判断交易量和交易数量

            //获取手续费比例
            $user = $this->request->user;
            $handfee = 0;
            if ($data['type'] == 2) {
                $handfeeratio = (new UserConfig())->where('level', $user['level'])->value('handfee');
                $handfeeratio = !empty($handfeeratio) ? $handfeeratio / 100 : 0;
                $handfee = round($data['num'] * $handfeeratio, 2);
                if ($user['quota'] < $data['num']) {
                    $this->result([], 1, '出售额度不足');
                }
                if ($user['amount'] < ($data['num'] + $handfee)) {
                    $this->result([], 1, '您必须拥有额外' . $handfee . 'KCB才能发布');
                }
                $sellerid = $this->request->user_id;
            } else {
                $buyerid = $this->request->user_id;
            }
            $hallarr = [
                'logid' => time(),
                'user_id' => $this->request->user_id,
                'buyer_id' => $buyerid ?? 0,
                'seller_id' => $sellerid ?? 0,
                'num' => $data['num'],
                'handfee' => $handfee ?? 0,
                'price' => $data['price'],
                'status' => 1,
                'type' => $data['type']
            ];
            Db::startTrans();
            try {
                $id = (new HallTrade())->insertGetId($hallarr);
                if ($data['type'] == 2) {
                    (new Users())->MoneyEdit($this->request->user_id, $user['amount'], -$data['num'], 2, 3, '售卖挂单', $id, 0, $handfee, 0);
                    //手续费操作
                    if ($handfee > 0) {
                        (new Users())->MoneyEdit($this->request->user_id, ($user['amount'] - $data['num']), -$handfee, 2, 4, '售卖挂单手续费', $id, 0, $handfee, 0);
                    }
                    //额度操作
                    (new Users())->MoneyEdit($this->request->user_id, $user['quota'], -$data['num'], 3, 2, '售卖挂单', $id, 0, $handfee, 0);
                }
                Db::commit();
            } catch (\Exception $e) {
                dump($e->getMessage());
                Db::rollback();
                $this->result([], 1, '提交失败，请重试');
            }
            $this->result([], 0, '提交成功');
        }
    }

    public function MyHallOrder()
    {
        $status = $this->request->get('status/d', '');
        $list = (new HallTrade())->order('id desc');
        if (!empty($status)) {
            if ($status == 1) {
                $list = $list->where(['status' => [1, 2, 3, 6, 7]]);
            } else {
                $list = $list->where(['status' => [4, 5]]);
            }
        } else {
            $list = $list->where(['status' => [1, 2, 3, 4, 5, 6, 7]]);
        }
        $list = $list->where('user_id', $this->request->user_id)->field('logid,updated', true)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists->status_name = $lists->status_name;
            if ($lists['buyer_id'] == $this->request->user_id) {
                $lists['types'] = 2;
            } else {
                $lists['types'] = 1;
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function OrderDetail()
    {
        $id = $this->request->get('id/d', 0);
        $order = (new HallTrade())->where('id', $id)->field('logid,user_id,updated', true)->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        if ($order['buyer_id'] != $this->request->user_id && $order['seller_id'] != $this->request->user_id) {
            //$this->result([], 1, '无权限');
        }
        if ($order['buyer_id'] == $this->request->user_id) {
            $order['mobile'] = (new Users())->where('id', $order['seller_id'])->value('mobile');
            $order['safety'] = (new UserSafety())->where('user_id', $order['seller_id'])->field('id,user_id,created,updated', true)->select();
            $order['ordertype'] = 2;
        }
        if ($order['seller_id'] == $this->request->user_id) {
            $order['mobile'] = (new Users())->where('id', $order['buyer_id'])->value('mobile');
            $order['ordertype'] = 1;
        }
        $order['status_text'] = $order->status_name;
        $order['ordersn'] = pow(12, 10) + $order['id'];
        $this->result($order, 0, '获取成功');
    }

    public function MyOrder()
    {
        $type = $this->request->get('type/d', '');
        $status = $this->request->get('status/d', '');
        $list = (new HallTrade())->order('id desc');
        if (!empty($type)) {
            if ($type == 1) {
                $list = $list->where('buyer_id', $this->request->user_id);
            } else {
                $list = $list->where('seller_id', $this->request->user_id);
            }
        }
        if (!empty($status)) {
            if ($status == 5) {
                $list = $list->where(['status' => [6, 7]]);
            } elseif ($status == 6) {
                $list = $list->where(['status' => [4, 5]]);
            } else {
                $list = $list->where(['status' => $status]);
            }
        } else {
            $list = $list->where(['status' => [2, 3, 4, 5, 6, 7]]);
        }
        $list = $list->field('logid,updated', true)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            if ($lists['buyer_id'] == $this->request->user_id) {
                $lists['types'] = 2;
            } else {
                $lists['types'] = 1;
            }
            $lists->status_name = $lists->status_name;
        }
        $this->result($list, 0, '获取成功');
    }

    public function Cacel()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'trade' => 'require'
            ], [
                'id.require' => 'Id不能为空',
                'id.gt' => 'Id必须大于0',
                'trade.require' => '交易密码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if (md5(md5($data['trade'])) != $user['trade']) {
                $this->result([], 1, '交易密码错误');
            }
            $order = (new HallTrade())->where(['id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在');
            }
            if ($order['buyer_id'] != $this->request->user_id && $order['seller_id'] != $this->request->user_id) {
                $this->result([], 1, '非交易用户无法操作');
            }
            if ($order['status'] != 1 && $order['status'] != 2) {
                $this->result([], 1, '订单状态不可取消');
            }
            if ($order['status'] != 1 && $order['seller_id'] == $this->request->user_id) {
                $this->result([], 1, '订单已匹配，卖家无法取消');
            }
            if ($order['buyer_id'] == $this->request->user_id) {
                $suser = (new Users())->where('id', $order['seller_id'])->find();
            }
            Db::startTrans();
            try {
                (new HallTrade())->where(['id' => $data['id']])->update(['status' => 5]);
                //卖家操作
                if ($order['seller_id'] == $this->request->user_id) {
                    (new Users())->MoneyEdit($this->request->user_id, $user['amount'], $order['num'], 2, 3, '取消订单', $order['id'], 0, 0, 0);
                    //手续费操作
                    if ($order['handfee'] > 0) {
                        (new Users())->MoneyEdit($this->request->user_id, ($user['amount'] + $order['num']), $order['handfee'], 2, 4, '取消挂单手续费', $order['id'], 0, 0, 0);
                    }
                    //额度操作
                    (new Users())->MoneyEdit($this->request->user_id, $user['quota'], $order['num'], 3, 2, '售卖挂单取消', $order['id'], 0, 0, 0);
                    //信誉值操作
                    (new Users())->where('id', $this->request->user_id)->setDec('reputa', 1);
                }
                //买家操作
                if ($order['buyer_id'] == $this->request->user_id) {
                    if ($order['status'] == 2) {
                        (new Users())->MoneyEdit($order['seller_id'], $suser['amount'], $order['num'], 2, 3, '取消订单', $order['id'], 0, 0, 0);
                        //手续费操作
                        if ($order['handfee'] > 0) {
                            (new Users())->MoneyEdit($order['seller_id'], ($suser['amount'] + $order['num']), $order['handfee'], 2, 4, '取消挂单手续费', $order['id'], 0, 0, 0);
                        }
                        //额度操作
                        (new Users())->MoneyEdit($order['seller_id'], $suser['quota'], $order['num'], 3, 2, '售卖挂单取消', $order['id'], 0, 0, 0);
                    }
                    //信誉值操作
                    (new Users())->where('id', $this->request->user_id)->setDec('reputa', 1);
                }
                Db::commit();
            } catch (\Exception $e) {
                dump($e->getMessage());
                Db::rollback();
                $this->result([], 1, '取消失败，请重试');
            }
            $this->result([], 0, '取消成功');
        }
    }

    //匹配订单
    public function MatchOrder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'trade' => 'require'
            ], [
                'id.require' => 'Id不能为空',
                'id.gt' => 'Id必须大于0',
                'trade.require' => '交易密码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if (md5(md5($data['trade'])) != $user['trade']) {
                $this->result([], 1, '交易密码错误');
            }
            if ($user['reputa'] < 1) {
                $this->result([], 1, '信誉值过低');
            }
            $transopen = (new Config())->where('key', 'transopen')->value('value');
            $transopen = empty($transopen) ? 2 : $transopen;
            if ($transopen != 1) {
                $this->result([], 1, '交易市场已关闭');
            }

            $order = (new HallTrade())->where(['id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在');
            }
            if ($order['status'] != 1) {
                $this->result([], 1, '订单状态不可匹配');
            }
            if ($order['buyer_id'] == $this->request->user_id || $order['seller_id'] == $this->request->user_id) {
                $this->result([], 1, '无法匹配自己的订单');
            }
            if ($order['type'] == 1) {
                $hallconfig = (new Config())->where('key', 'hall')->value('value');
                $hallconfig = json_decode($hallconfig, true);
                if (empty($hallconfig['allmax']) || empty($hallconfig['count'])) {
                    $this->result([], 1, '系统参数错误');
                }
                $facount = (new HallTrade())->where(['seller_id' => $this->request->user_id])->where('matchtime', '>=', date('Y-m-d'))->where(['status' => 4])->count();
                if ($facount >= $hallconfig['count']) {
                    $this->result([], 1, '每天售卖次数不能超过' . $hallconfig['count'] . "次");
                }
                $fasum = (new HallTrade())->where('seller_id', $this->request->user_id)->where('matchtime', '>=', date('Y-m-d'))->where(['status' => 4])->sum('num');
                if (($fasum + $order['num']) >= $hallconfig['allmax']) {
                    $this->result([], 1, '每天累计售卖不能超过' . $hallconfig['allmax']);
                }
            }
            //有交易中的订单无法继续发布
            $haveorder = (new HallTrade())->where('buyer_id|seller_id', $this->request->user_id)->where(['status' => [1, 2, 3, 6, 7]])->count();
            if ($haveorder > 0) {
                $this->result([], 1, '请先完成交易订单再继续操作');
            }
            $matchorderrds = Redis::get('matchorder' . $data['id']);
            if ($matchorderrds) {
                $this->result([], 1, '订单匹配中，为防止重复匹配，请稍后再试');
            }
            Redis::setex('matchorder' . $data['id'], 3, '订单匹配中');
            //买单判断手续费和币种数量
            if ($order['type'] == 1) {
                $handfeeratio = (new UserConfig())->where('level', $user['level'])->value('handfee');
                $handfeeratio = !empty($handfeeratio) ? $handfeeratio / 100 : 0;
                $handfee = round($order['num'] * $handfeeratio, 2);
                if ($user['quota'] < $order['num']) {
                    $this->result([], 1, '出售额度不足');
                }
                if ($user['amount'] < ($order['num'] + $handfee)) {
                    $this->result([], 1, '您必须拥有额外' . $handfee . 'KCB才能售卖');
                }
                $buyerid = $order['buyer_id'];
                $sellerid = $this->request->user_id;
            } else {
                $buyerid = $this->request->user_id;
                $sellerid = $order['seller_id'];
            }
            Db::startTrans();
            try {
                (new HallTrade())->where(['id' => $data['id']])->update([
                    'status' => 2,
                    'handfee' => $handfee ?? 0,
                    'buyer_id' => $buyerid,
                    'seller_id' => $sellerid,
                    'matchtime' => date('Y-m-d H:i:s')
                ]);
                if ($order['type'] == 1) {
                    (new Users())->MoneyEdit($this->request->user_id, $user['amount'], -$order['num'], 2, 3, 'OTC售卖', $order['id'], 0, $handfee, 0);
                    //手续费操作
                    if ($handfee > 0) {
                        (new Users())->MoneyEdit($this->request->user_id, ($user['amount'] - $order['num']), -$handfee, 2, 4, 'OTC售卖手续费', $order['id'], 0, $handfee, 0);
                    }
                    //额度操作
                    (new Users())->MoneyEdit($this->request->user_id, $user['quota'], -$order['num'], 3, 2, 'OTC售卖', $order['id'], 0, $handfee, 0);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '匹配失败，请重试');
            }
            $this->result([], 0, '匹配成功');
        }
    }

    //订单付款
    public function PayOrder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'payimages' => 'require',
                'trade_type' => 'require|in:1,2,3',
                'trade' => 'require'
            ], [
                'id.require' => 'Id不能为空',
                'id.gt' => 'Id必须大于0',
                'payimages.require' => '付款凭证不能为空',
                'trade_type.require' => '付款类型不能为空',
                'trade_type.in' => '付款类型不正确',
                'trade.require' => '交易密码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if (md5(md5($data['trade'])) != $user['trade']) {
                $this->result([], 1, '交易密码错误');
            }
            $order = (new HallTrade())->where(['id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在');
            }
            if ($order['status'] != 2) {
                $this->result([], 1, '订单状态不可付款');
            }
            if ($order['buyer_id'] != $this->request->user_id) {
                $this->result([], 1, '非买家用户，无法操作');
            }
            Db::startTrans();
            try {
                (new HallTrade())->where(['id' => $data['id']])->update([
                    'status' => 3,
                    'payimages' => $data['payimages'],
                    'trade_type' => $data['trade_type'],
                    'paycreated' => date('Y-m-d H:i:s')
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败，请重试');
            }
            $this->result([], 0, '操作成功');
        }
    }

    //订单确认
    public function EndOrder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'trade' => 'require'
            ], [
                'id.require' => 'Id不能为空',
                'id.gt' => 'Id必须大于0',
                'trade.require' => '交易密码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if (md5(md5($data['trade'])) != $user['trade']) {
                $this->result([], 1, '交易密码错误');
            }
            $order = (new HallTrade())->where(['id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在');
            }
            if ($order['status'] != 3) {
                $this->result([], 1, '订单状态不可确认');
            }
            if ($order['seller_id'] != $this->request->user_id) {
                $this->result([], 1, '非卖家用户，无法操作');
            }
            $buyuser = (new Users())->where('id', $order['buyer_id'])->find();
            if (empty($buyuser)) {
                $this->result([], 1, '买家返款出错，请联系管理员');
            }
            $quota = 0;
            $quotaratio = (new Config())->where('key', 'hallquote')->value('value');
            $quotaratio =  $quotaratio ?? 1.5;
            $quota = round($order['num'] * $quotaratio, 2);
            Db::startTrans();
            try {
                (new HallTrade())->where(['id' => $data['id']])->update(['status' => 4]);
                //买家币和信誉
                if ($order['num'] > 0) {
                    (new Users())->MoneyEdit($buyuser['id'], $buyuser['money'], $order['num'], 1, 2, 'OTC购买', $order['id']);
                    //额度操作
                    (new Users())->MoneyEdit($buyuser['id'], $buyuser['quota'], $quota, 3, 1, 'OTC购买', $order['id']);
                }
                //信誉值操作
                (new Users())->where('id', $order['seller_id'])->setDec('reputa', 1);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败，请重试');
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function CompOrder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'info' => 'require'
            ], [
                'id.require' => 'Id不能为空',
                'id.gt' => 'Id必须大于0',
                'info.require' => '投诉理由不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!empty($data['images'])) {
                $images = json_decode($data['images'], true);
                if (empty($images)) {
                    $this->result([], 1, '图片上传格式错误');
                }
            }
            $user = $this->request->user;
            $order = (new HallTrade())->where(['id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在');
            }
            if ($order['status'] != 2 && $order['status'] != 3) {
                $this->result([], 1, '订单状态不可申诉');
            }
            if ($order['status'] == 2 && $order['buyer_id'] == $user['id']) {
                $this->result([], 1, '未付款状态买家请选择取消');
            }
            if ($order['seller_id'] != $user['id'] && $order['buyer_id'] != $user['id']) {
                $this->result([], 1, '非交易玩家订单无法操作');
            }
            if ($order['buyer_id'] == $user['id']) {
                $status = 6;
            }
            if ($order['seller_id'] == $user['id']) {
                $status = 7;
            }
            Db::startTrans();
            try {
                (new HallTrade())->where(['id' => $data['id']])->update(['status' => $status]);
                (new HallApple())->insert([
                    'user_id' => $user['id'],
                    'hallid' => $order['id'],
                    'info' => $data['info'],
                    'images' => $data['images'] ?? '',
                    'status' => 1
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '申诉失败，请重试');
            }
            $this->result([], 0, '申诉成功，请等待管理员审核');
        }
    }
}
